import { defineStore } from 'pinia'
import { get, urlToParams } from '@common'
import {
  getLocalData,
  getToken,
  setToken,
  removeToken,
  handleTree,
  setLocalData,
  removeLocalData,
  goLogin,
  del
} from '@common'
import { loadView, routerPush } from '@/utils'
import { MessagePlugin } from 'tdesign-vue-next'
import { microViews } from '@/router'
const HOME_COMPONENT = 'home/index' // 主页组件地址
const HOME_PATH = 'board' // 主页路由地址
export const useSystem = defineStore('system', {
  state: () => ({
    token: getToken(),
    userInfo: {}, //用户数据
    deptList: [], // 部门数据
    rolesList: [], //角色列表
    quickList: getLocalData('quickList') || [], // 浏览列表
    menuList: [], //全部菜单-树形
    menuFlatList: [], //全部菜单-一级
    asideMenuList: [], //当前权限侧边栏数据
    routers: [], //当前权限路由
    tenantPackageList: {},
    permissions: [] //权限
  }),
  actions: {
    async getUserInfo() {
      const res = await get('system/user/getInfo')
      this.userInfo = res.user
      this.permissions = res.permissions || []
      setLocalData('permissions', this.permissions)
    },
    setUserInfo(data) {
      this.userInfo = data || {}
      this.permissions = data?.permissions || []
      setLocalData('permissions', this.permissions)
    },
    async getDeptList(params) {
      const res = await get('system/dept/list', params)
      const list = res.data
      return handleTree(list, { id: 'deptId', labelKey: 'deptName' })
    },
    async getDeptListAll() {
      const list = await this.getDeptList()
      this.deptList = list
    },
    async getRolesListAll() {
      const res = await get('system/role/list', {
        pageNum: 1,
        pageSize: 1000
      })
      const list = res.data
      this.rolesList = list.map((e) => {
        return {
          ...e,
          label: e.roleName,
          value: e.roleId
        }
      })
    },
    async setQuickList(quickItem) {
      const newList = [...this.quickList]
      const index = newList.findIndex((e) => e.path == quickItem.path)
      if (index >= 0) {
        // newList.splice(index, 1)
      } else {
        newList.push(quickItem)
      }
      // newList.unshift(quickItem)
      if (newList.length > 6) {
        newList.shift()
      }
      setLocalData('quickList', newList)
      this.quickList = newList
    },
    async getMenuList(params) {
      const res = await get('system/menu/list', params)
      const list = res.data
      const treeList = handleTree(list, { id: 'menuId', labelKey: 'menuName' })
      return {
        list,
        treeList
      }
    },
    async getMenuListAll() {
      const { list, treeList } = await this.getMenuList()
      this.menuFlatList = list
      this.menuList = treeList
    },
    setToken(token) {
      this.token = token
      if (!token) {
        removeToken()
      } else {
        setToken(token)
      }
    },
    // 当前权限路由
    async getRouters() {
      const showMenuList = []
      const res = await get('system/menu/getRouters')
      const menus = res.data
      if (!menus?.length) {
        return MessagePlugin.warning('没有访问权限，请联系管理员授权')
      }
      const menuList = JSON.parse(JSON.stringify(menus))
      let routeItem = null
      let curRouteFullPath = window.location.hash.replace('#/', '')
      const curRoutePath = curRouteFullPath.split('?')[0]
      const pushShowMenuList = (e) => {
        let children = (e.children || []).filter((item) => !item.hidden)
        children = JSON.parse(JSON.stringify(children))
        children = children.filter((e) => e.path != '/chat/index')
        if (!e.hidden && (children.length > 0 || e.path === `/${HOME_PATH}`)) {
          showMenuList.push({ ...e, children })
        }
      }
      const handleMetaLinkApp = (e) => {
        if (e.meta.link) {
          const link = e.meta.link.replace(/https:\/\//i, '')
          const microName = link.split('/').shift()
          const path = link.replace(microName, '')
          e.path = path
          e.name = path
          e.component = microViews[microName] || loadView()
          // 用于区分微服务
          e.microName = microName
          if (e.children) {
            e.children = e.children.map((d) => {
              return {
                ...d,
                path: d.path.replace(`/${microName}`, ''),
                componentName: d.component,
                component: microViews[microName]
              }
            })
          }
        }
      }
      menuList.forEach((e) => {
        e.meta = e.meta || {}
        // 处理首页
        // if(e.)
        // 处理微服务外链
        handleMetaLinkApp(e)
        if (e.children) {
          e.children.forEach(handleMetaLinkApp)
        }
        // 是否需要重定向
        if (!routeItem && curRouteFullPath) {
          let item = null
          if (e.path.includes(curRoutePath)) {
            item = e
          } else {
            item = (e.children || []).find((d) => d.path?.includes(curRoutePath))
          }
          if (item) {
            routeItem = { ...item }
          }
        }
        // 重定向
        e.redirect = e.children?.[0]?.path || ''
        // 处理外链或微服务
        if (e.meta.link) {
          pushShowMenuList(e)
        } else {
          if (e.children) {
            e.component = loadView(e.component)
            const childrens = []
            e.children = e.children.map((d) => {
              if (!d.hidden) {
                childrens.push({ ...d })
              }
              d.component = loadView(d.component)
              return d
            })
            pushShowMenuList({
              ...e,
              children: childrens
            })
          } else if (e.path === `/${HOME_PATH}`) {
            e.component = loadView(HOME_COMPONENT)
            pushShowMenuList(e)
          } else {
            pushShowMenuList(e)
          }
        }
      })
      menuList.sort((a) => {
        if (a.hidden || (a?.children || []).filter((e) => !e.hidden).length == 0) {
          return -1
        }
        return 1
      })
      // 动态添加路由
      menuList.forEach((e) => {
        window.$router.addRoute('layout', e)
      })

      if (!routeItem) {
        if (menuList.find((e) => e.path == '/' + HOME_PATH)) {
          routeItem = menuList.find((e) => e.path == '/' + HOME_PATH)
        } else {
          routeItem = showMenuList?.[0]?.children?.[0] || showMenuList[0]
        }
      }
      if (routeItem?.path) {
        routerPush({
          ...routeItem,
          query: urlToParams(window.location.href)
        })
      }
      this.asideMenuList = showMenuList
      this.routers = menuList
    },
    setRouters(data) {
      this.asideMenuList = data
      this.routers = data
    },
    // 获取租户合作模式id,type:1，供应商。2:项目负责人
    async getTenantPackageByType(type) {
      const res = await get(`system/tenantpackage/get-simple-list?tenantType=${type}`)
      const option = res.data.map((item) => ({
        label: item.name,
        value: item.id
      }))
      this.tenantPackageList[type] = option
      return option
    },
    async loginOut() {
      await del('auth/logout')
      removeToken()
      goLogin()
      removeLocalData('tenant-id')
      removeLocalData('channel')
      removeLocalData('permissions')
      setTimeout(() => {
        window.location.reload()
      }, 50)
    }
  }
})
